import { initTRPC, TRPCError } from '@trpc/server'
import { z } from 'zod'
import { RegisterSchema, LoginSchema, CreateUserSchema, UpdateUserSchema, GetUsersQuerySchema } from '@shared/types'
import { AuthService } from './services/auth.service.js'
import { UserService } from './services/user.service.js'

// 初始化 tRPC
const t = initTRPC.context().create()

// 导出 router 和 procedure
export const router = t.router
export const publicProcedure = t.procedure

// 创建服务实例
const authService = new AuthService()
const userService = new UserService()

// 定义应用路由
export const appRouter = router({
  // ========== 认证相关接口 ==========

  // Mutation 操作：用户注册
  register: publicProcedure.input(RegisterSchema).mutation(async ({ input }) => {
    try {
      return await authService.register(input)
    } catch (error: any) {
      throw new TRPCError({
        code: error.message.includes('邮箱') ? 'CONFLICT' : 'BAD_REQUEST',
        message: error.message || '注册失败'
      })
    }
  }),

  // Mutation 操作：用户登录
  login: publicProcedure.input(LoginSchema).mutation(async ({ input }) => {
    try {
      return await authService.login(input)
    } catch (error: any) {
      throw new TRPCError({
        code: 'UNAUTHORIZED',
        message: error.message || '登录失败'
      })
    }
  }),

  // ========== 用户管理接口 ==========

  // Query 操作：获取用户列表
  getUsers: publicProcedure.input(GetUsersQuerySchema).query(async ({ input }) => {
    try {
      return await userService.getUsers({
        limit: input.limit,
        offset: input.offset,
        sex: input.sex
      })
    } catch (error: any) {
      throw new TRPCError({
        code: 'INTERNAL_SERVER_ERROR',
        message: error.message || '获取用户列表失败'
      })
    }
  }),

  // Query 操作：根据 UID 获取用户
  getUserByUid: publicProcedure.input(z.object({ uid: z.string().uuid('UID 必须是有效的 UUID') })).query(async ({ input }) => {
    try {
      return await userService.getUserByUid(input.uid)
    } catch (error: any) {
      throw new TRPCError({
        code: 'NOT_FOUND',
        message: error.message || `用户 UID ${input.uid} 未找到`
      })
    }
  }),

  // Mutation 操作：创建用户
  createUser: publicProcedure.input(CreateUserSchema).mutation(async ({ input }) => {
    try {
      return await userService.createUser(input)
    } catch (error: any) {
      throw new TRPCError({
        code: error.message.includes('邮箱') ? 'CONFLICT' : 'INTERNAL_SERVER_ERROR',
        message: error.message || '创建用户失败'
      })
    }
  }),

  // Mutation 操作：更新用户
  updateUser: publicProcedure
    .input(
      z.object({
        uid: z.string().uuid('UID 必须是有效的 UUID'),
        data: UpdateUserSchema
      })
    )
    .mutation(async ({ input }) => {
      try {
        return await userService.updateUser(input.uid, input.data)
      } catch (error: any) {
        if (error.message.includes('未找到')) {
          throw new TRPCError({
            code: 'NOT_FOUND',
            message: error.message
          })
        }
        throw new TRPCError({
          code: 'INTERNAL_SERVER_ERROR',
          message: error.message || '更新用户失败'
        })
      }
    }),

  // Mutation 操作：删除用户
  deleteUser: publicProcedure.input(z.object({ uid: z.string().uuid('UID 必须是有效的 UUID') })).mutation(async ({ input }) => {
    try {
      const deletedUser = await userService.deleteUser(input.uid)
      return { success: true, deleted: deletedUser }
    } catch (error: any) {
      if (error.message.includes('未找到')) {
        throw new TRPCError({
          code: 'NOT_FOUND',
          message: error.message
        })
      }
      throw new TRPCError({
        code: 'INTERNAL_SERVER_ERROR',
        message: error.message || '删除用户失败'
      })
    }
  })
})

export type AppRouter = typeof appRouter
